package com.yangrd.helper.crudhelper.core.crud.page.impl;

import com.yangrd.helper.crudhelper.core.crud.page.CrudPage;
import com.yangrd.helper.crudhelper.core.crud.page.CrudPageRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * description: MemoryCrudPageRepository
 *
 * @author: yangrd
 * @date: 2020/10/23
 * @version: 1.0
 */
public class MemoryCrudPageRepository implements CrudPageRepository {

    private Map<Class<?>, CrudPage> class2CrudPage = new HashMap<>();

    @Override
    public Optional<CrudPage> get(Class<?> domainClass) {
        return Optional.ofNullable(class2CrudPage.get(domainClass));
    }

    @Override
    public void put(Class<?> domainClass, CrudPage crudPage) {
        class2CrudPage.put(domainClass, crudPage);
    }

    @Override
    public void delete(Class<?> domainClass) {
        class2CrudPage.remove(domainClass);
    }

    @Override
    public Page<CrudPage> findAll(String domain, Pageable pageable) {
        List<CrudPage> list = class2CrudPage.keySet().stream().filter(domainClass -> domain==null||domainClass.getSimpleName().contains(domain)).map(this.class2CrudPage::get).collect(Collectors.toList());
        List<CrudPage> content = list.subList(pageable.getPageSize() * pageable.getPageNumber(), Math.min(pageable.getPageSize() * (pageable.getPageNumber() + 1), list.size()));
        return new PageImpl<>(content, pageable, list.size());
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
